from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from routers import user, material, record, agent, mindMap, knowledge_card
from models.models import Base
from database import engine
from utils.log_manager import app_logger
from config import settings

app = FastAPI()

# 创建数据库表（如果不存在）
try:
    Base.metadata.create_all(bind=engine)
except Exception as e:
    app_logger.error("数据库连接异常：" + str(e))

# 添加 CORS 中间件配置
app.add_middleware(
    CORSMiddleware,
    allow_origins=[settings.allowed_origins],  # 允许前端访问
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册路由
app.include_router(agent.router, prefix="/api", tags=["readPage"])
app.include_router(user.router, prefix="/api", tags=["user"])
app.include_router(material.router, prefix="/api", tags=["material"])
app.include_router(record.router, prefix="/api", tags=["record"])
app.include_router(mindMap.router, prefix="/api", tags=["mindMap"])
app.include_router(knowledge_card.router, prefix="/api", tags=["card"])

if __name__ == "__main__":
    import uvicorn
    from uvicorn.config import LOGGING_CONFIG

    # 添加文件处理器
    LOGGING_CONFIG["handlers"]["file"] = {
        "class": "logging.handlers.RotatingFileHandler",
        "formatter": "default",
        "filename": "static/logs/web.logs",
        "maxBytes": 1024 * 1024 * 20,  # 20 MB
        "backupCount": 5,
        "encoding": "utf-8",
    }

    # 配置各个日志器，同时禁止日志传播
    LOGGING_CONFIG["loggers"]["uvicorn"]["handlers"] = ["default", "file"]
    LOGGING_CONFIG["loggers"]["uvicorn"]["propagate"] = False

    LOGGING_CONFIG["loggers"]["uvicorn.access"]["handlers"] = ["default", "file"]
    LOGGING_CONFIG["loggers"]["uvicorn.access"]["propagate"] = False

    LOGGING_CONFIG["loggers"]["uvicorn.error"]["handlers"] = ["default", "file"]
    LOGGING_CONFIG["loggers"]["uvicorn.error"]["propagate"] = False

    uvicorn.run(app, host="0.0.0.0", port=settings.port, log_config=LOGGING_CONFIG)